//
//  TestRtspAppDelegate.m
//  TestRtsp
//
//  Created by wangweike on 11-2-26.
//  Copyright __MyCompanyName__ 2011. All rights reserved.
//

#import "TestRtspAppDelegate.h"
#import "VideoDecoder.h"

@implementation TestRtspAppDelegate

@synthesize window;

static void * memalign(size_t align, size_t sz)
{
	/* this a hack so that runlog can link with mallocs that don't have */
	/* memalign */
	void *p = malloc(sz + align + 1);
	size_t d = (unsigned long)p % align;
	
	if (d != 0)
		p = (char *)p + align - d;
	
	return p;
}

int posix_memalign(void **memptr, size_t alignment, size_t size)
{
	/* Make sure alignment is correct. */
	if (alignment % sizeof(void *) != 0)
	/* Skip these checks because the memalign() func does them for us
	 34	         || !powerof2(alignment / sizeof(void *)) != 0
	 35	         || alignment == 0
	 36	         */
		return EINVAL;
	
	*memptr = memalign(alignment, size);
	
	return (*memptr != NULL ? 0 : ENOMEM);
}


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {    

    // Override point for customization after application launch
	
	iImageViewController=[[ImageViewController alloc] init];
	[window addSubview:iImageViewController.view];
    [window makeKeyAndVisible];
	
	//定时
	iTimer = [NSTimer scheduledTimerWithTimeInterval:5 target:self selector:@selector(onTimer) userInfo:nil repeats:NO];

	
	return YES;
}

-(void)onTimer
{
	iTimer=nil;
	
	
	//rtsp://vod1.3g.youku.com/03002001004D671CE6611C0073F0EDF9825FF9-6A09-1673-BD09-DCCD31C37232.mp4
	//rtsp://video3.americafree.tv/AFTVComedyH2641000.sdp
	//rtsp://192.168.1.252/mpeg4
	iRtspSession = [[RTSPClientSession alloc] initWithURL:[NSURL URLWithString:@"rtsp://video3.americafree.tv/AFTVComedyH2641000.sdp"]];
	[iRtspSession setup];
	
	//sdp
	printf([[ iRtspSession getSDP ]UTF8String]);
	
	NSArray *array =  [iRtspSession getSubsessions];
	for (int i=0; i < [array count]; i++) 
	{
		
		RTSPSubsession *subsession = [array objectAtIndex:i];
		
		
		[iRtspSession setupSubsession:subsession useTCP:YES ];
		subsession.delegate=self;       
		[subsession increaseReceiveBufferTo:2000000];           
		
		//NSLog(@"%@", [subsession getProtocolName]);
//		NSLog(@"%@", [subsession getCodecName]);
//		NSLog(@"%@", [subsession getMediumName]);
//		NSLog(@"%d", [subsession getSDP_VideoHeight]);
//		NSLog(@"%d", [subsession getServerPortNum]);
		
	}
	[iRtspSession play ];
	
	
	
	NSLog(@"error: --> %@",[ iRtspSession getLastErrorString ]);
	
	char* rawsdp=NULL;
	[iRtspSession runEventLoop:rawsdp];
}


- (void)dealloc {
    [window release];
    [super dealloc];
}

- (NSString *) directorioDocument{
	NSArray			*paths				= NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
	NSString		*documentsDirectory = [paths objectAtIndex:0];
	return documentsDirectory;
}

- (void)appendText:(NSData *)datos toFile:(NSString *)filePath {
	
	NSLog(filePath);
	
	// NSFileHandle won't create the file for us, so we need to check to make sure it exists
    NSFileManager *fileManager = [NSFileManager defaultManager];
    if (![fileManager fileExistsAtPath:filePath]) {
		
		// the file doesn't exist yet, so we can just write out the text using the 
		// NSString convenience method
		
		
        BOOL success = [datos writeToFile:filePath atomically:YES ];
        if (!success) {
			// handle the error
            NSLog(@"error");
        }
		
    } else {
		
	 	// the file already exists, so we should append the text to the end
		
		// get a handle to the file
        NSFileHandle *fileHandle = [NSFileHandle fileHandleForWritingAtPath:filePath];
		
		// move to the end of the file
        [fileHandle seekToEndOfFile];
		// write the data to the end of the file
        [fileHandle writeData:datos];
		
		// clean up
        [fileHandle closeFile];
		
    }
}


- (void)didReceiveFrame:(const uint8_t*)frameBuffer
		frameDataLength:(int)frameDataLength
	   presentationTime:(struct timeval)presentationTime
 durationInMicroseconds:(unsigned)duration
			 subsession:(RTSPSubsession*)subsession
{
	NSLog(@"didReceiveFrame");
	
	
	NSData *frameData = [NSData dataWithBytesNoCopy:(void*)frameBuffer length:frameDataLength freeWhenDone:NO];

	//[self appendText:frameData toFile:[[self directorioDocument] stringByAppendingString:@"/video.mp4"]];
	//NSLog(@"%@",presentationTime);
	
	
	if(!iVideoDecoder)
	{
		int width=320;
		int height=480;
		[VideoDecoder staticInitialize];
		iVideoDecoder = [[VideoDecoder alloc]initWithCodec:kVCT_H264 colorSpace:kVCS_RGBA32 width:width height:height privateData:frameData];
	}
	
	[iVideoDecoder decodeFrame:frameData];
	 NSData *decodedData =[iVideoDecoder getDecodedFrame];
	// [videoDecoder release];
	// [self appendText:decodedData toFile:[[self getFilePath] stringByAppendingString:@"/video.h264"]];
	 
	
	//[self appendText:frameData toFile:[[self getFilePath] stringByAppendingString:@"/video.h264"]];
	//NSLog(@"%@",presentationTime);
	 
	UIImage* image=[[UIImage alloc] initWithData:decodedData];//decodedData
	[iImageViewController.iImageView setImage:image];
	 
}


//- (void)didReceiveFrame:(NSData*)frameData presentationTime:(NSDate*)presentationTime
//{	
//	/*
//	 [VideoDecoder staticInitialize];
//	 videoDecoder = [[VideoDecoder alloc]initWithCodec:kVCT_H264 colorSpace:kVCS_RGBA32 width:576 height:768 privateData:frameData];
//	 [videoDecoder decodeFrame:frameData];
//	 NSData *decodedData =[videoDecoder getDecodedFrame];
//	 [videoDecoder release];
//	 [self appendText:decodedData toFile:[[self getFilePath] stringByAppendingString:@"/video.h264"]];
//	 */
//
//	//[self appendText:frameData toFile:[[self getFilePath] stringByAppendingString:@"/video.h264"]];
//	NSLog(@"%@",presentationTime);
//}



@end
